package Netty.Reactor模型;

import java.io.IOException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 著作权归https://pdai.tech所有。
 * 链接：https://pdai.tech/md/java/io/java-io-nio-select-epoll.html
 *
 * 主要有四个角色：客户端连接，Reactor，Acceptor和Handler。
 * 这里Acceptor会不断地接收客户端的连接，
 * 然后将接收到的连接交由Reactor进行分发，最后有具体的Handler进行处理
 * 
 * 
 * Acceptor：处理客户端连接事件
 */
public class Acceptor implements Runnable {
    
    private final ExecutorService executor = Executors.newFixedThreadPool(20);

    private final ServerSocketChannel serverSocket;

    public Acceptor(ServerSocketChannel serverSocket) {
        this.serverSocket = serverSocket;
    }

    @Override
    public void run() {
        try {
            SocketChannel channel = serverSocket.accept();  // 获取客户端连接
            if (null != channel) {
                executor.execute(new Handler(channel));  // 将客户端连接交由线程池处理
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
